package controllers

import (
	"encoding/json"
	"errors"
	"qysoft/models"
	//	"strconv"
	"github.com/astaxie/beego"
	"qysoft/libs/encrypt"
	"strings"

	// "strconv"
	"time"
)

// OrganizationController oprations for Organization
type OrganizationController struct {
	CommonController
}

// URLMapping 方法映射
func (c *OrganizationController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	c.Mapping("GetOrganizationList", c.GetOrganizationList)
	//	c.Mapping("DeleteOrgs", c.DeleteOrgs)
	//	c.Mapping("StatisticPage", c.StatisticPage)
	//	c.Mapping("StatisticOrgs", c.StatisticOrgs)
}

// Post  create Organization
// @Title Post
// @Description create Organization
// @Param	body		body 	models.Organization	true		"body for Organization content"
// @Success 201 {int} models.Organization
// @Failure 403 body is empty
// @router / [post]
func (c *OrganizationController) Post() {
	var v models.Organization
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	// rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	err = json.Unmarshal(rdata, &v)

	// sdata, _ := rdata.(map[string]interface{})
	// v.Name, _ = sdata["Name"].(string)
	v.Code = encrypt.GetGuid()
	// //	regid, _ := sdata("RegId").(string)
	v.RegId = "0"
	// ulimit, _ := sdata["Userlimit"].(string)
	// v.Userlimit, _ = strconv.Atoi(ulimit)
	// //	v.Userlimit = 99999999
	// v.Phone, _ = sdata["Phone"].(string)
	// v.FeeType, _ = sdata["FeeType"].(string)
	// v.Contact, _ = sdata["Contact"].(string)
	v.Pid = "0"
	v.Btime = time.Now()
	v.Etime = v.Btime.Add(99999 * time.Hour)
	// v.Abbr, _ = sdata["Abbr"].(string)
	// v.Title, _ = sdata["Title"].(string)
	// v.Logo, _ = sdata["Logo"].(string)
	// vtype, _ := sdata["Type"].(string)
	// vstatus, _ := sdata["Status"].(string)
	// v.Pid = sdata["Pid"].(string)
	// //	v.Pid, _ = strconv.ParseInt(vpid, 10, 64)
	// v.Status, _ = strconv.Atoi(vstatus)
	// v.Type, _ = strconv.Atoi(vtype)

	v.Seq = 100
	// v.OrderCode = "-"
	// v.OrderId = "-"
	// v.ProdId = "-"
	v.Creater = user.Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	v.Id = encrypt.GetGuid()
	_, err = models.AddOrganization(&v)
	if err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)

	}
	var dept models.Dept
	dept.Pid = "0"
	dept.Name = v.Abbr
	dept.Remark = "本部"
	dept.Level = 0
	dept.Status = 1
	dept.Isdelete = 0
	dept.Organization = &v
	dept.Creater = v.Creater
	dept.Ctime = v.Ctime
	dept.Updater = v.Updater
	dept.Utime = v.Utime
	dept.Id = encrypt.GetGuid()
	if _, err := models.AddDept(&dept); err != nil {
		beego.Debug(err)
		c.RetError(ErrDatabase)

	}
	// c.Dlog("添加了客户单位", v.Id)
	// rt := make(map[string]interface{})
	// rt["id"] = v.Id
	// c.RetSuccess(rt)
	beego.Debug(v)
	beego.Debug(err)
	c.RetSuccess(v)
}

// GetOne get Organization by id
// @Title Get
// @Description get Organization by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Organization
// @Failure 403 :id is empty
// @router /:id [get]
func (c *OrganizationController) GetOne() {
	id := c.GetString(":id")
	v, err := models.GetOrganizationById(id)
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// GetAll get Organization
// @Title Get All
// @Description get Organization
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Organization
// @Failure 403
// @router / [get]
func (c *OrganizationController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	query := make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}
	limit = -1
	query["Isdelete"] = "0"
	l, err := models.GetAllOrganization(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(l)
}

// Update update the Organization
// @Title Update
// @Description update the Organization
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Organization	true		"body for Organization content"
// @Success 200 {object} models.Organization
// @Failure 403 :id is not int
// @router /Update [post]
func (c *OrganizationController) Update() {
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var v models.Organization
	err = json.Unmarshal(rdata, &v)
	if err != nil {
		c.RetError(ErrInputData)
	}
	u, _ := models.GetOrganizationById(v.Id)
	// v = u
	v.Updater = user.Name
	v.Utime = time.Now()
	if err := models.UpdateOrganizationById(&v); err == nil {
		c.Dlog("修改了客户单位", v.Id, 1, u)
		c.RetSuccess(v)
	}
	c.RetError(ErrDatabase)

}

// Delete delete the Organization
// @Title Delete
// @Description delete the Organization
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *OrganizationController) Delete() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	//	id, err := strconv.ParseInt(sid, 10, 64)
	if err != nil {
		c.RetError(ErrInputData)
	}
	err = models.SoftDeleteOrganization(id, user.Name)
	if err != nil {
		c.RetError(ErrDatabase)
	}

	c.Dlog("删除了客户单位", id)
	rt := make(map[string]interface{})
	rt["Id"] = id
	c.RetSuccess(rt)

}

// GetOrganizationList 返回有效单位列表
// @Title GetOrganizationListelete
// @Description 返回有效单位列表
// @Success 200
// @Failure 403
// @router /GetOrganizationList [get]
func (c *OrganizationController) GetOrganizationList() {
	var fields []string
	var sortby []string
	var order []string
	var limit int64 = -1
	var offset int64
	query := make(map[string]string)
	query["status"] = "1"
	query["isdelete"] = "0"
	fields = append(fields, "Id", "Name")

	l, err := models.GetAllOrganization(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	}
	c.RetSuccess(l)
}
